package com.technology.education.wxapi

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.coroutineScope
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.ext.postEventBus
import com.technology.education.ext.showLoadingExt
import com.technology.education.ext.showLog
import com.technology.education.ext.toast
import com.technology.education.network.apiService
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_OK
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.launch
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException

/**
 *@author:create by BZY
 *Date: 2022/5/16 08
 */
class WXEntryActivity : AppCompatActivity(), IWXAPIEventHandler {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val api = WXAPIFactory.createWXAPI(this, AppData.WX_ID, true)
        api.handleIntent(intent, this)
    }


    override fun onReq(p0: BaseReq?) {
        showLog("onReq-------------${p0}")
    }

    override fun onResp(p0: BaseResp?) {
        showLog("onResp---${p0?.errCode}")
        p0?.let {
            if (it.errCode == ERR_OK && it.type == 1) {
                val code = (it as SendAuth.Resp).code
                getWxInfo(code)
            }else{
                toast("已取消绑定")
                finish()
            }
        }
    }

    private fun getWxInfo(code: String?) {
        showLoadingExt()
        val http = OkHttpClient()
        Thread {
            try {
                val response = http.newCall(
                    Request.Builder()
                        .url("https://api.weixin.qq.com/sns/oauth2/access_token?appid=${AppData.WX_ID}&secret=ab7bee437a5d9032b6ba79225ef47e80&code=$code&grant_type=authorization_code")
                        .get().build()
                )
                response.enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        runOnUiThread {
                            toast("获取信息失败")
                            finish()
                        }
                    }

                    override fun onResponse(call: Call, response: Response) {
                        if (response.code() == 200) {
                            val result = response.body()?.string()
                            showLog(result ?: "")
                            val json = JSONObject(result)
                            val infoRes = http.newCall(
                                Request.Builder().url(
                                    "https://api.weixin.qq.com/sns/userinfo?access_token=${
                                        json.getString(
                                            "access_token"
                                        )
                                    }&openid=${json.getString("openid")}"
                                ).get().build()
                            )
                            infoRes.enqueue(object : Callback {
                                override fun onFailure(call: Call, e: IOException) {

                                }

                                override fun onResponse(call: Call, response: Response) {
                                    if (response.code() == 200) {
                                        val infoResult = response.body()?.string()
                                        postEventBus(SpKeys.WX_INFO, infoResult ?: "")
                                        finish()
                                    } else {
                                        runOnUiThread {
                                            toast("获取信息失败")
                                            finish()
                                        }

                                    }
                                }

                            })

                        } else {
                            runOnUiThread {
                                toast("获取信息失败")
                                finish()
                            }
                        }
                    }

                })

            } catch (e: IOException) {
                runOnUiThread {
                    toast("获取信息失败")
                    finish()
                }
            } catch (e: JSONException) {
                runOnUiThread {
                    toast("获取信息失败")
                    finish()
                }
            }
        }.start()
    }
}